//
//  EDJBaseAsynchronousOperation.m
//  EDJCoreFramework
//
//  Created by 王芳 on 16/4/22.
//  Copyright © 2016年 edaijia-inc. All rights reserved.
//

#import "EDJBaseAsynchronousOperation.h"

@interface EDJBaseAsynchronousOperation ()
@property (nonatomic,getter=isFinished,readwrite) BOOL finished;
@property (nonatomic,getter=isExecuting,readwrite) BOOL executing;
@end

@implementation EDJBaseAsynchronousOperation

@synthesize finished = _finished;
@synthesize executing = _executing;

- (instancetype)init{
    self = [super init];
    if (self) {
        _finished = NO;
        _executing = NO;
    }
    return self;
}

- (void)start{
    
    self.executing = YES;
    [self main];
}

- (void)main{
    NSAssert(![self isMemberOfClass:[EDJBaseAsynchronousOperation class]], @"EDJBaseAsynchronousOperation is abstract class that must be subclassed");
    NSAssert(false, @"EDJBaseAsynchronousOperation subclasses must override `main`.");
}

- (void)completeOperation{
    self.finished = YES;
    self.executing = NO;
}

#pragma mark- property

- (BOOL)isAsynchronous{
    return YES;
}

- (BOOL)isFinished{
    @synchronized(self) {
        return _finished;
    }
}

- (BOOL)isExecuting{
    @synchronized(self) {
        return _executing;
    }
}

- (void)setFinished:(BOOL)finished{
    if (_finished != finished) {
        [self willChangeValueForKey:@"isFinished"];
        @synchronized(self) {
            _finished = finished;
        }
        [self didChangeValueForKey:@"isFinished"];
    }
}

- (void)setExecuting:(BOOL)executing{
    if (_executing != executing) {
        [self willChangeValueForKey:@"isExecuting"];
        @synchronized(self) {
            _executing = executing;
        }
        [self didChangeValueForKey:@"isExecuting"];
    }
}
@end
